package cn.yunyichina.provider.hisiface.invoke.impl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import cn.yunyichina.provider.hisiface.http.HttpServerConfig;
import cn.yunyichina.provider.hisiface.invoke.IOutsideInvoke;
import cn.yunyichina.provider.hisiface.invoke.OutsideInvokeServiceFactory;
import cn.yunyichina.provider.hisiface.sdk.security.Base64Method;
import cn.yunyichina.provider.hisiface.sdk.util.MD5Utils;
import cn.yunyichina.provider.hisiface.sdk.util.MapUtils;
import cn.yunyichina.provider.hisiface.util.ServiceRouter;
import cn.yunyichina.provider.iface.entity.base.OrgSettingVoResponse;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.commons.StringUtils;
import cn.yunyichina.utils.convert.JsonUtils;

import com.alibaba.fastjson.JSON;

@Service
public class OutsideInvokeServiceImpl {

	private static final Logger logger = LoggerFactory.getLogger(OutsideInvokeServiceImpl.class);
	
	@SuppressWarnings("unchecked")
	public String openService(Map<String, String> httpContent) throws Exception {
		// 业务参数
		String data = httpContent.get("data");
		String jsonContent = Base64Method.decryptUrlSafeBase64(data);
		Map<String, String> params = JSON.parseObject(jsonContent, Map.class);
		
		String hospitalCode = params.get("hospital_code");
		String noauth = params.get("NOAUTH");
		boolean verifySignature = verifySignature(hospitalCode, noauth, httpContent);
		if (!verifySignature) {
			logger.error("验证签名失败");
			return JsonUtils.toJsonString(new Response("4105", ""));
		}
		
		String method = httpContent.get("method");
		String className = OutsideInvokeServiceFactory.getOpenserviceMap().get(method);
		if (StringUtils.isNullOrBlank(className)) {
			return JsonUtils.toJsonString(new Response("4106", "接口未实现: " + method));
		} else {
			IOutsideInvoke outsideService = OutsideInvokeServiceFactory.getInstance(className);
			return outsideService.execute(params);
		}
	}
	
	/**
	 * 验证签名
	 * 
	 * @param hospitalCode
	 * @param noauth
	 * @param httpContent
	 * @return
	 */
	private boolean verifySignature(String hospitalCode, String noauth, Map<String, String> httpContent) {
		// 免验签开关
		String noAuthSwitch = HttpServerConfig.getConfig().getNoAuthSwitch();
		if ("true".equalsIgnoreCase(noauth) && "on".equalsIgnoreCase(noAuthSwitch)) {
			// 不用验证签名
			return true;
		}
		
		OrgSettingVoResponse orgSetting = ServiceRouter.getFrontInfo(httpContent.get("sessionid"), hospitalCode, "", "");
		if (! ServiceRouter.checkRouterMap(orgSetting)) {
			logger.error("openservice: 查询前置机服务地址失败，url为空或者signKey为空");
			return false;
		}
		
		String signKey = orgSetting.getSignKey();
		
		String encryptStr = MapUtils.coverMap2SignString(httpContent);
		String sign = MD5Utils.string2MD5(encryptStr + signKey);
		
		String frontSign = httpContent.get("sign");
		
		return sign.equals(frontSign);
	}

}
